package io.demo.petstore.account;

import java.util.Optional;
import org.apache.commons.lang3.StringUtils;


/**
 * the conditions below leads to validation failure
 * <ul>
 * <li>username is blank</li>
 * <li>username length is less than 6 after trim</li>
 * </ul>
 *
 * @author lijinting01
 */
public class UsernameValidator implements AccountValidator {

  private static final int MIN_LENGTH = 6;

  private static final int MAX_LENGTH = 255;

  @Override
  public boolean test(Account account) {
    String username = Optional.ofNullable(account)
        .map(Account::getUsername)
        .map(StringUtils::trim)
        .map(String::toLowerCase)
        .filter(s -> s.length() >= MIN_LENGTH && s.length() <= MAX_LENGTH)
        .orElse(null);

    return username != null;
  }


  @Override
  public AccountException accountException() {
    return new InvalidUsernameException();
  }
}
